package com.breachwalls.mogen.plugin.actions;

import java.io.File;
import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.breachwalls.mogen.plugin.Activator;
import com.breachwalls.mogen.plugin.generator.EclipseModelGeneratorConfigurer;
import com.breachwalls.mogen.plugin.generator.ModelGeneratorRunnableWithProgress;

public class RunMogenActionDelegate implements IObjectActionDelegate {

    private static Logger logger = LoggerFactory.getLogger(RunMogenActionDelegate.class);

    private Shell shell;

    private EclipseModelGeneratorConfigurer configurer = new EclipseModelGeneratorConfigurer();

    /**
     * Constructor for Action1.
     */
    public RunMogenActionDelegate() {
        super();
    }

    /**
     * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
     */
    public void setActivePart(IAction action, IWorkbenchPart targetPart) {
        shell = targetPart.getSite().getShell();
    }

    /**
     * @see IActionDelegate#run(IAction)
     */
    public void run(IAction action) {
        ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
        IRunnableWithProgress runnable = new ModelGeneratorRunnableWithProgress(configurer);
        try {
            dialog.run(true, true, runnable);
        } catch (InterruptedException e) {
            logger.debug("MOdel GENerator execution is cancelled.");
        } catch (InvocationTargetException e) {
            logger.error("MOdelGENerator has executed failure.", e);
            MessageDialog.openError(shell, "MOdel GENerator ERROR", e.getMessage());
        }
    }

    /**
     * @see IActionDelegate#selectionChanged(IAction, ISelection)
     */
    public void selectionChanged(final IAction action, final ISelection selection) {
        if (selection != null && selection instanceof IStructuredSelection) {
            IStructuredSelection structured = (IStructuredSelection) selection;
            Object o = structured.getFirstElement();
            if (o instanceof IProject) {
                // プロジェクト選択時に設定ファイル（あれば）を読み込む
                IProject project = (IProject) o;
                IFile file = project.getFile("mogen.properties");
                if (file.isAccessible()) {
                    IPath rootPath = project.getLocation();
                    IPath filePath = file.getLocation();

                    File selectionProject = new File(rootPath.toOSString());
                    File selectionFile = new File(filePath.toOSString());
                    configurer.setProject(project);
                    configurer.setProjectLocation(selectionProject);
                    configurer.setConfigLocation(selectionFile);

                    Activator plugin = Activator.getDefault();
                    IPath path = plugin.getStateLocation();
                    File pluginLocation = new File(path.toOSString());
                    configurer.setPluginLocation(pluginLocation);

                    logger.info("Processing Project : [" + project.getName() + "]");
                    logger.info("Project Path : [" + selectionProject.getAbsolutePath() + "]");
                    logger.info("ConfigFile Path : [" + selectionFile.getAbsolutePath() + "]");
                }
            }
        }
    }

}
